//
//  CYYCommentListViewController.m
//  LetsParty
//
//  Created by YG on 15/9/19.
//  Copyright (c) 2015年 LetsPartyTeam. All rights reserved.
//

#import "CYYCommentListViewController.h"
#import "CYYCommentTableViewCell.h"

static NSString * KUITableViewIdentifier = @"KUITableViewIdentifier";
static CGFloat usernameFontSize = 16;
static CGFloat timeFontSize = 10;
static CGFloat commentContentFontSize = 14;

@interface CYYCommentListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIScrollView * mainScrollView;//底层View
@property (nonatomic, strong) UITableView * mainTableView;
@property (nonatomic, strong) NSMutableArray * dataSourcesArray;//评论数据
@property (nonatomic, strong) UIView * commentView;//评论底层
@property (nonatomic, strong) UITextView * commentTextView;//评论框
@property (nonatomic, strong) UIButton * commentSenderButton;//评论发送按钮
@property (nonatomic, strong) UIButton * cancleSenderButton;//取消评论
@property (nonatomic, strong) UIButton * commentButton;//评论按钮

- (void)initializeDataSources;
- (void)updateDataSources;
- (void)initializeUserInterface;

@end

@implementation CYYCommentListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
}

- (void)viewWillAppear:(BOOL)animated{
    [self initializeDataSources];
}

#pragma mark - system protrol methods
//组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataSourcesArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.f;
}

//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cCell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

    return cCell.frame.size.height + 30;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CYYCommentTableViewCell * cCell = [[CYYCommentTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:KUITableViewIdentifier];
    cCell.selectionStyle = UITableViewCellSelectionStyleNone;
    cCell.userNameLabel.text = _dataSourcesArray[indexPath.section][@"commentAuthorName"];
    cCell.userNameLabel.font = [UIFont systemFontOfSize:usernameFontSize];
    cCell.userNameLabel.textColor = [UIColor blackColor];
    cCell.tiemLabel.text = _dataSourcesArray[indexPath.section][@"createdAt"];
    cCell.tiemLabel.font = [UIFont systemFontOfSize:timeFontSize];
    cCell.tiemLabel.tintColor = [UIColor darkGrayColor];
    cCell.commmenContentLabel.text = _dataSourcesArray[indexPath.section][@"commentContent"];
    cCell.commmenContentLabel.font = [UIFont systemFontOfSize:commentContentFontSize];
    cCell.commmenContentLabel.tintColor = [UIColor blackColor];
//    [cCell.supportButton setImage:[UIImage imageNamed:@"iconfont-zandes"] forState:UIControlStateNormal];
//    [cCell.supportButton setImage:[UIImage imageNamed:@"iconfont-zanse"] forState:UIControlStateSelected];
//    [cCell.supportButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    cCell.textLabel.numberOfLines = 0;
//    cCell.updateSupportDelegate = self;
//    cCell.supportButton.tag = 100 + indexPath.section;
    //自适应高度
    //需要计算的文本:评论内容
    NSString * contentString = _dataSourcesArray[indexPath.section][@"commentContent"];
    //大小约束
    CGSize size = [contentString boundingRectWithSize:CGSizeMake(280, MAXFLOAT)   options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:commentContentFontSize]} context:nil].size;
    CGRect rect = cCell.frame;
    rect.size.height = size.height + 30;
    cCell.frame = rect;
    cCell.commmenContentLabel.frame = DHFlexibleFrame(CGRectMake(40, 30, 260, rect.size.height), NO);
    cCell.commmenContentLabel.font = [UIFont systemFontOfSize:commentContentFontSize];
    return cCell;
}
//Button协议
- (void)updateSupport:(UIButton *)button{
    button.selected = !button.selected;
}

#pragma mark - responds event
- (void)respondsToLeftButton:(UIButton *)button{
    [[ControllerManager sharedManager].rootViewController popViewControllerAnimated:YES];
}

- (void)respondsToSenderButton:(UIButton *)button{
    button.userInteractionEnabled = NO;
    if ([self.commentTextView.text isEqualToString:@""]) {
//        NSLog(@"评论内容不能为空");
        UIAlertController * alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"评论内容不能为空" preferredStyle:UIAlertControllerStyleAlert];
        [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alterController animated:YES completion:nil];
        button.userInteractionEnabled = YES;
        return;
    }
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager commentAPartyWithObjectId:myVC.partyObjectId comment:myVC.commentTextView.text sucess:^(NSString *sucessString) {
        myVC.commentView.hidden = YES;
        [myVC.commentTextView resignFirstResponder];
        [myVC updateDataSources];
        [myVC clearAllCommentContent];
        button.userInteractionEnabled = YES;
    } fail:^(NSError *error) {
        button.userInteractionEnabled = YES;
    }];
}

- (void)respondsToCancleButton:(UIButton *)button{
    self.commentView.hidden = YES;
    [self.commentTextView resignFirstResponder];
}

- (void)respondsToCommnetButton:(UIButton *)button{
    button.userInteractionEnabled = NO;
    if ([[UserModel defaultUser] isAlreadyLoad]) {
        self.commentView.hidden = NO;
        [self.commentTextView becomeFirstResponder];
        button.userInteractionEnabled = YES;
    }else{
        [[[ControllerManager sharedManager] rootViewController]presentViewController:[ControllerManager sharedManager].loadViewController animated:YES completion:nil];
        button.userInteractionEnabled = YES;
    }
}

#pragma mark - private methods
- (void)initializeDataSources{
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager newCommentListWithPartyObjectId:myVC.partyObjectId sucess:^(NSArray *array) {
        _dataSourcesArray = [array mutableCopy];
        [myVC.mainTableView reloadData];
    } fail:^(NSError *error) {
        
    }];
}
//刷新数据
- (void)updateDataSources{
    __weak typeof(self) myVC = self;
    __block NSMutableArray * mDataArray = [NSMutableArray array];
    [CYYNetWorkManager newCommentListWithPartyObjectId:myVC.partyObjectId sucess:^(NSArray *array) {
        mDataArray = [array mutableCopy];
        if (_dataSourcesArray.count == 0) {
            _dataSourcesArray = [array mutableCopy];
            [myVC.mainTableView reloadData];
        }else{
            for (int i = 0; i < array.count; i ++) {
                if ([_dataSourcesArray[0][@"objectId"] isEqualToString:array[i][@"objectId"]]) {
                    [mDataArray removeObjectsInRange:NSMakeRange(i, array.count - i)];
                    _dataSourcesArray = [[mDataArray arrayByAddingObjectsFromArray:_dataSourcesArray] mutableCopy];
                    [myVC.mainTableView reloadData];
                    break;
                }
            }
        }
    } fail:^(NSError *error) {
        
    }];
}

- (void)initializeUserInterface{
    self.baseNavigationBar.backgroundColor = [UIColor whiteColor];
    self.bartitleLabel.text = @"所有评论";
    [self.leftNavButton setImage:[UIImage imageNamed:@"iconfont-zuojiantou"] forState:UIControlStateNormal];
    [self.leftNavButton addTarget:self action:@selector(respondsToLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mainTableView];
    [self.commentView addSubview:self.commentTextView];
    [self.commentView addSubview:self.commentSenderButton];
    [self.commentSenderButton addTarget:self action:@selector(respondsToSenderButton:) forControlEvents:UIControlEventTouchUpInside];
    self.commentView.hidden = YES;
    [self.view addSubview:self.commentButton];
    [self.commentButton addTarget:self action:@selector(respondsToCommnetButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.commentView addSubview:self.cancleSenderButton];
    [self.cancleSenderButton addTarget:self action:@selector(respondsToCancleButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.commentView];
}

//清理评论内容
- (void) clearAllCommentContent{
    self.commentTextView.text = @"";
}

#pragma mark - getter
- (UITableView *)mainTableView{
    if (!_mainTableView) {
        _mainTableView = ({
            UITableView * tTableView = [[UITableView alloc]initWithFrame:DHFlexibleFrame(CGRectMake(0, 64, 320, 504), NO) style:UITableViewStyleGrouped];
            tTableView.delegate = self;
            tTableView.dataSource = self;
            [tTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:KUITableViewIdentifier];
            tTableView;
        });
    }
    return _mainTableView;
}

- (UIView *)commentView{
    if (!_commentView) {
        _commentView = ({
            UIView * cView = [[UIView alloc]init];
            cView.frame = DHFlexibleFrame(CGRectMake(0, 64, 320, 504), NO);
            cView.backgroundColor = [UIColor colorWithWhite:0.4 alpha:0.4];
            cView;
        });
    }
    return _commentView;
}

- (UITextView *)commentTextView{
    if (!_commentTextView) {
        _commentTextView = ({
            UITextView * cTextView = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, 300, 120)adjustWidth:NO];
            cTextView.layer.borderWidth = 0.5f;
            cTextView.layer.borderColor = [UIColor blackColor].CGColor;
            cTextView;
        });
    }
    return _commentTextView;
}

-(UIButton *)cancleSenderButton{
    if (!_cancleSenderButton) {
        _cancleSenderButton = ({
            UIButton * cButton = [UIButton buttonWithType:UIButtonTypeCustom];
            cButton.frame = DHFlexibleFrame(CGRectMake(10, 150, 40, 20), NO);
            cButton.backgroundColor = [UIColor darkGrayColor];
            [cButton setTitle:@"取消" forState:UIControlStateNormal];
            cButton;
        });
    }
    return _cancleSenderButton;
}

- (UIButton *)commentSenderButton{
    if (!_commentSenderButton) {
        _commentSenderButton = ({
            UIButton * cButton = [UIButton buttonWithType:UIButtonTypeCustom];
            cButton.frame = DHFlexibleFrame(CGRectMake(270, 150, 40, 20), NO);
            cButton.backgroundColor = COLOR_TagBlue;
            [cButton setTitle:@"发送" forState:UIControlStateNormal];
            cButton;
        });
    }
    return _commentSenderButton;
}

- (UIButton *)commentButton{
    if (!_commentButton) {
        _commentButton = ({
            UIButton * cButton = [UIButton buttonWithType:UIButtonTypeCustom];
            cButton.frame = DHFlexibleFrame(CGRectMake(220, 420, 80, 80), NO);
            cButton.layer.masksToBounds = YES;
            cButton.layer.cornerRadius = 40 * DHFlexibleVerticalMutiplier();
            [cButton setImage:[UIImage imageNamed:@"ljp"] forState:UIControlStateNormal];
            [cButton setTitle:@"评论" forState:UIControlStateNormal];
            cButton;
        });
    }
    return _commentButton;
}


@end
